package com.fruit.listener;

import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.annotation.PostConstruct;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fruit.constants.OrderConstant;
import com.fruit.constants.QueueConstant;
import com.fruit.pojo.order.DSHOrder;
import com.fruit.pojo.queue.Cache;
import com.fruit.pojo.queue.QueueParams;
import com.fruit.service.order.DelayHandel;
import com.fruit.service.order.DelayHandel.OnDelayedListener;
import com.fruit.service.order.OrderHandel;
import com.fruit.service.order.QueueHandel;
import com.fruit.service.order.QueueHandel.OnQueueListener;
import com.fruit.service.queue.QueueBusHandel;
import com.fruit.service.redis.JedisUtil;
import com.fruit.util.CommonUtil;
import com.joe.utils.parse.json.JsonParser;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class StartupListener {

	@Autowired
	private DelayHandel delayService;

	@Autowired
	private QueueHandel queueService;

	@Autowired
	private OrderHandel orderHandel;

	@Autowired
	private QueueBusHandel queueBusService;

	@Autowired
	private JedisUtil jedisService;

	private static final JsonParser JSON = JsonParser.getInstance();

	public final static ExecutorService OrderThreadPool = Executors.newFixedThreadPool(9);

	@PostConstruct
	public void init() {
		log.info("【开启监听】");
		delayService.start(new OnDelayedListener() {

			@Override
			public void onDelayedArrived(final DSHOrder order) {

				OrderThreadPool.execute(new Runnable() {
					@Override
					public void run() {
						// 处理订单
						String tradeId = CommonUtil.getUUID();
						log.info("[{}]-【取消订单】-【开始】-【订单号：{}】", tradeId, order.getOrderId());
						if (order.getOrderId() != 0) {
							long isDel = jedisService.hdel(OrderConstant.ORDER_AUTO_CANCEL, order.getOrderId() + "");
							log.info("[{}]-【取消订单】-【删除redis】-【删除结果：{}】", tradeId, isDel);
							if (isDel == 1) {
								orderHandel.autoCancelOrder(tradeId, order, 3);
							}
						}
						log.info("[{}]-【取消订单】-【结束】", tradeId);
					}
				});

			}
		});

		queueService.start(new OnQueueListener() {

			// 同步处理
			@Override
			public void onSynQueueArrived(QueueParams params) {
				// 处理业务
				String tradeId = CommonUtil.getUUID();
				log.info("[{}]-【queue同步队列】-【处理开始】-【参数：{}】", tradeId, params);
				long isDel = jedisService.hdel(QueueConstant.MULTIL_PROFIT, params.getKey());
				log.info("[{}]-【queue同步队列】-【删除redis】-【删除结果：{}】", tradeId, isDel);
				if (isDel == 1) {
					queueBusService.handel(params);
				}
			}

			// 异步处理
			@Override
			public void onAsynQueueArrived(QueueParams params) {
				OrderThreadPool.execute(new Runnable() {
					@Override
					public void run() {
						// 处理业务
						String tradeId = CommonUtil.getUUID();
						log.info("[{}]-【queue异步队列】-【处理开始】-【参数：{}】", tradeId, params);
						long isDel = jedisService.hdel(QueueConstant.MULTIL_PROFIT, params.getKey());
						log.info("[{}]-【queue异步队列】-【删除redis】-【删除结果：{}】", tradeId, isDel);
						if (isDel == 1) {
							queueBusService.handel(params);
						}
					}
				});
			}
		});

		// 从缓存读取取消订单
		OrderThreadPool.execute(new Runnable() {
			@Override
			public void run() {
				String tradeId = CommonUtil.getUUID();

				log.info("[{}]-【从缓存读取取消订单】-【开始】", tradeId);
				Map<String, String> keys = jedisService.hgetAll(OrderConstant.ORDER_AUTO_CANCEL);
				if (keys == null || keys.size() <= 0) {
					return;
				}

				// 写到DelayQueue
				for (String key : keys.keySet()) {
					String value = keys.get(key);
					log.info("[{}]-【从缓存读取取消订单】-【KEY：{}】-【VALUE：{}】", tradeId, key, value);
					if (StringUtils.isNotEmpty(value)) {
						DSHOrder dshOrder = new DSHOrder(Long.parseLong(key), Long.parseLong(value));
						delayService.add(dshOrder);
					}
				}
				log.info("[{}]-【从缓存读取取消订单】-【结束】", tradeId);
			}
		});

		// 从缓存读取活动队列
		OrderThreadPool.execute(new Runnable() {
			@Override
			public void run() {
				String tradeId = CommonUtil.getUUID();
				log.info("[{}]-【从缓存读取多级分润数据】-【开始】", tradeId);
				try {

					// 扫描redis，找到所有可能的orderId
					Map<String, String> keys = jedisService.hgetAll(QueueConstant.MULTIL_PROFIT);
					if (keys == null || keys.size() <= 0) {
						return;
					}
					// 写到DelayQueue
					for (String key : keys.keySet()) {

						String value = keys.get(key);
						log.info("[{}]-【从缓存读取多级分润数据】-【KEY：{}】-【VALUE：{}】", tradeId, key, value);
						if (StringUtils.isNotEmpty(value)) {
							Cache cache = JSON.readAsObject(value, Cache.class);
							@SuppressWarnings("unchecked")
							QueueParams params = JSON.readAsObject(cache.getData(),
									(Class<? extends QueueParams>) Class.forName(cache.getClassName()));

							queueService.add(params, true);
						}
					}
				} catch (Exception e) {
					log.error("[{}]-【从缓存读取多级分润数据】-【异常】", tradeId);
				}

				log.info("[{}]-【从缓存读取多级分润数据】-【结束】", tradeId);
			}
		});

	}
}
